package com.swh.context;

import com.alibaba.druid.pool.DruidDataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

import java.io.IOException;

/**
 * @Author: swh
 * @Description:
 * @Date: 2020/12/10 16:25
 * @Version: 1.0
 */


@Configuration
@ComponentScan("com.swh")
@PropertySource(value = "classpath:db.properties")
@EnableWebMvc
@MapperScan("com.swh.dao")
public class App implements WebMvcConfigurer {

    @Value("${jdbc.driverClassName}")
    private String driverClass;
    @Value("${jdbc.url}")
    private  String url;
    @Value("${jdbc.username}")
    private String username;
    @Value("${jdbc.password}")
    private String password;


    @Bean
    public DruidDataSource getDataSource(){
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(driverClass);
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);

        return dataSource;
    }

    @Bean
    public SqlSessionFactoryBean getFactoryBean(DruidDataSource dataSource) throws IOException {

        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();

        factoryBean.setDataSource(dataSource);

        factoryBean.setTypeAliasesPackage("com.swh.entity");

//        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
//
//        Resource[] resources = resolver.getResources("classpath:/com/swh/dao/*.xml");
//
//        factoryBean.setMapperLocations(resources);

        return factoryBean;
    }

    //容器管理视图bean
    @Bean
    public InternalResourceViewResolver getResourvler(){
        return  new InternalResourceViewResolver("/WEB-INF/jsp/",".jsp");
    }

    //配置默认静态资源放行
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();//放行静态资源
    }

}
